/**
 * Created by cxg on 2017/4/26.
 */
//创建数据库
import {
    Platform,
} from 'react-native';

const Realm = require('realm');
import Constant from '../constant/constant.js';
import ToastUtil from '../utils/toast-util';
import Http from '../utils/http';
import {Loading, EasyLoading} from 'react-native-easy-loading';

var DeviceInfo = require('react-native-device-info');

let realm;
let inited = false;

class InitDB {

    version = Constant.version;

    /*static getRealm = () => {
        return realm;
    }*/

    static init() {
        //alert('dbVersion:'+Constant.dbVersion);
        realm = new Realm({
            schemaVersion: Constant.dbVersion,

            schema: [
                // {
                //         name:"DAY_FIRST_OPEN",
                //         primaryKey:"test",
                //         properties:{
                //             test:'string',

                //         }
                // },

                {
                    name: Constant.TABLE_CURRENT_USER,
                    primaryKey: "username",
                    properties: {
                        username: 'string',
                        empId: 'string',
                        FIRST_OPEN_TIME: 'string',
                        pwd: 'string'
                    }
                },
                {
                    name: "cacheDataVersion",
                    primaryKey: "obj",
                    properties: {
                        empId: {type: "string"},
                        obj: {type: "string"},
                        hashCode_: "string"
                    }
                },

                {
                    name: Constant.TABLE_APP_INFO,
                    primaryKey: 'VERSION',
                    properties: {
                        VERSION: 'string',
                        OS: 'string',
                        OS_VERSION: 'string',
                        MOBILE_BRAND: 'string',
                        IMEI: 'string'
                    }
                },
                {
                    name: 'USERINFO',
                    primaryKey: 'ID',
                    properties: {
                        ID: 'string',
                        EMP_ID: {type: 'string', indexed: true},
                        ACVT_CODE: {type: 'string', indexed: true},
                        QST_CODE: 'string',
                        OPT_VAL: 'string',
                    }
                }, {
                    name: 'TIMES',
                    primaryKey: 'ID',
                    properties: {
                        ID: 'string',
                        bizDate: 'string'


                    }
                },


            ],


            migration: function (oldRealm, newRealm) {

            }

            /* migration: function(oldRealm, newRealm) {
                 ToastUtil.show('old:'+oldRealm.schemaVersion+";new:"+newRealm.schemaVersion);
                 // only apply this change if upgrading to schemaVersion 1

                 for(i=oldRealm.schemaVersion+1;i<=newRealm.schemaVersion;i++){

                      if (i===2) {
                     var oldObjects = oldRealm.objects('COURSE_USER');
                     var newObjects = newRealm.objects('COURSE_USER');

                     // loop through all objects and set the name property in the new schema
                     for (var i = 0; i < oldObjects.length; i++) {
                         newObjects[i].empId = oldObjecs[i].empId;
                     }

                 }
                 }

              }*/
        });


        let deviceInfo = InitDB.getDeviceInfo();

        //获取version
        let app_info_record = realm.objects(Constant.TABLE_APP_INFO);

        // ToastUtil.show('deviceInfo.osVersion:'+deviceInfo.osVersion);

        if (app_info_record.length === 0) {

            realm.write(() => {

                realm.create('APP_INFO', {
                    VERSION: Constant.version,
                    OS: deviceInfo.os + "",
                    OS_VERSION: deviceInfo.osVersion + "",
                    MOBILE_BRAND: deviceInfo.mobileBrand + "",
                    IMEI: deviceInfo.imei + ""

                });
            })
            app_info_record = realm.objects(Constant.TABLE_APP_INFO);
        }

        let isUpdate = false;
        if (app_info_record.VERSION != Constant.version) {
            isUpdate = true;
        }


        if (isUpdate) {

            realm.write(() => {
                realm.delete(realm.objects('APP_INFO'));

                realm.create('APP_INFO', {
                    VERSION: Constant.version,
                    OS: deviceInfo.os + "",
                    OS_VERSION: deviceInfo.osVersion + "",
                    MOBILE_BRAND: deviceInfo.mobileBrand + "",
                    IMEI: deviceInfo.imei + ""

                });
            })

        }


        /*测试代码 */
        // realm.write(() => {
        //     realm.delete( realm.objects("CURRENT_USER"))
        // })

        // 判断日期
        let date = new Date();

        let time = date.getYear() + '' + date.getMonth() + '' + date.getDate();


        let objs = realm.objects('CURRENT_USER');

        if (objs[0]) {
            if (objs[0].FIRST_OPEN_TIME == time) {
                // alert('已登录状态，当天打开过app')
                //当天已打开过，不做处理
            } else {
                // alert('已登录状态，当天没有打开过app')
                //当天没有打开过app，模拟登录一遍
                let url = '/mobile/login.do?action=login';
                let params = {
                    username: objs[0].username,
                    password: objs[0].pwd,
                    cacheDataVersion: InitDB.getCacheDataVersionByCurrentUser(),

                }
                //==============================================调用登录方法，自动登录===================

                // Http.post(url, 'login', objs[0].username, params)
                //     .then(res => {
                //         // /alert('111');
                //         if (res.result_code === 0) {
                //             Promise.resolve().then(EasyLoading.dismis());
                //             ToastUtil.show("登陆失败:" + res.result_desc);
                //         } else {

                //             let date = new Date();

                //             let time1 = date.getYear() + '' + date.getMonth() + '' + date.getDate();

                //             res.time = time1;

                //             // alert('模拟登录成功');

                //             InitDB.loginDataToDB(res);
                //             Promise.resolve().then(EasyLoading.dismis());

                //             ToastUtil.show("登陆成功:" + res.result_desc);

                //         }

                //     }).catch(err => {
                //     //请求失败
                //     Promise.resolve().then(EasyLoading.dismis());
                //     ToastUtil.show('登陆失败，错误信息:' + err);
                //     // ToastUtil.show('登陆失败，错误信息:' + err);

                // })

                //====================================调用登录方法，自动登录===================

            }
        } else {
            // alert('没有登录过')
        }


    }


    static getDeviceInfo() {
        return {
            os: Platform.OS,
            osVersion: DeviceInfo.systemVersion,
            platform: DeviceInfo.model,
            mobileBrand: DeviceInfo.brand,
            imei: DeviceInfo.uniqueID

        }
    }


    static loginDataToDB(json, callback) {
        inited = false;
        try {
            realm.write(() => {
                /*节点版本信息 */
                if (json.cacheDataVersion) {
                    realm.delete(realm.objects('cacheDataVersion'));
                    let cacheDataVersion = json.cacheDataVersion;
                    for (var prop in json.cacheDataVersion) {
                        if (json.cacheDataVersion.hasOwnProperty(prop)) {

                            if (cacheDataVersion[prop] + "" != 'deleted') {
                                realm.create('cacheDataVersion', {
                                    obj: prop,
                                    hashCode_: '' + cacheDataVersion[prop],
                                    empId: '' + json.empId
                                });
                            }
                        }
                    }
                }

                if (json.empId) {
                    realm.delete(realm.objects('CURRENT_USER'));
                    realm.create('CURRENT_USER', {
                        empId: '' + json.empId,
                        username: '' + json.username,
                        FIRST_OPEN_TIME: '' + json.time,
                        pwd: json.pwd + ''
                    });
                }

                if (json.userInfo) {
                    realm.delete(realm.objects('USERINFO'));
                    //  realm.delete(realm.objects('ACVTDIS').filtered("EMP_ID='" + json.empId + "'"));
                    if (json.userInfo != 'deleted') {
                        let userInfo = json.userInfo;
                        for (var i = 0; i < userInfo.length; i++) {
                            var value = userInfo[i];

                            if (value.OPT_VAL) {
                                realm.create('USERINFO', {
                                    ID: '' + value.empId + value.ACVT_CODE + value.QST_CODE,
                                    EMP_ID: '' + value.empId,
                                    ACVT_CODE: '' + value.ACVT_CODE,
                                    QST_CODE: '' + value.QST_CODE,
                                    OPT_VAL: '' + value.OPT_VAL

                                });
                            }
                        }
                    }
                }
                inited = true;
                if (callback) {
                    callback();
                }
            });
        } catch (e) {
            alert('写数据库报错:' + e);
        }

        //============================版本升级====================================
        if (json.updateUrl) {
            let Platform = require('Platform');
            if (Platform.OS === 'android') {
                NativeModules.DownloadApk.downloading(json.updateUrl, 'shequnsiwei.apk');
            } else {
                alert('版本有更新，请到appstore下载最新版')
            }
        }
        //============================版本升级====================================
    }


    static getCurrentUser() {
        let app_info_record = realm.objects(Constant.TABLE_CURRENT_USER);
        if (app_info_record && app_info_record.length > 0) {
            // alert(app_info_record.username);
            // return null;
            let record = new Object();
            record.empId = app_info_record[0].empId;
            record.username = app_info_record[0].username;
            record.FIRST_OPEN_TIME = app_info_record[0].time;
            record.pwd = app_info_record.pwd;

            return record;
        } else {
            return {
                empId:"",
            };
        }
    }


    static getBizDate() {
        let bizDate = realm.objects('TIMES').bizDate;
        if (!bizDate) {
            let date = new Date();
            bizDate = date.Format('yyyy-MM-dd');
        }

        return bizDate;
    }

    static logout() {
        let userinfo = InitDB.getCurrentUser();
        if (userinfo) {
            realm.write(() => {
                realm.delete(realm.objects("CURRENT_USER"));
            });
        }

    }

    static getVoices(filterSql) {
        let realmObjs;
        if (filterSql) {
            realmObjs = realm.objects('VOICES').filtered(filterSql);
        } else {
            realmObjs = realm.objects('VOICES');

        }

        let voices = [];
        for (let i = 0; i < realmObjs.length; i++) {
            let voice = new Object();
            voice.ID_ = realmObjs[i].ID_;
            voice.COURSE_ID = realmObjs[i].COURSE_ID;
            voice.FREE_ = realmObjs[i].FREE_;
            voice.IMAGE_ = realmObjs[i].IMAGE_;
            voice.TITLE1 = realmObjs[i].TITLE1;
            voice.TITLE2 = realmObjs[i].TITLE2;
            voice.KEY = realmObjs[i].KEY;
            voice.URL_ = realmObjs[i].URL_;
            voice.ORDER_ = realmObjs[i].ORDER_;
            //voice.TIME_ = realmObjs[i].TIME_;
            // voice.SECONDS_ = realmObjs[i].SECONDS_;
            voices.push(voice);
        }
        return voices;
    }

    /*
    name: "cacheDataVersion",
    primaryKey: "obj",
    properties: {
        empId: { type: "string" },
        obj: { type: "string" },
        hashCode_: "string"
    }
    */
    static getCacheDataVersionByCurrentUser() {
        let realmObjs;
        realmObjs = realm.objects('cacheDataVersion').filtered("empId='" + InitDB.getCurrentUser().empId + "'");
        let arr = {};
        for (let i = 0; i < realmObjs.length; i++) {
            let item = realmObjs[i];
            arr[item.obj] = item.hashCode_;
        }
        return arr;
    }


    static getUserInfo(filteredSql) {
        let realmObjs;
        if (filteredSql) {
            realmObjs = realm.objects('USERINFO').filtered("EMP_ID='" + InitDB.getCurrentUser().empId + "' AND " + filteredSql);
        } else {
            realmObjs = realm.objects('USERINFO').filtered("EMP_ID='" + InitDB.getCurrentUser().empId + "'");
        }
        return realmObjs;

        let arr = [];
        for (let i = 0; i < realmObjs.length; i++) {
            let obj = new Object();
            let item = realmObjs[i];
            obj.ID = item.ID;
            obj.ACVT_CODE = item.ACVT_CODE;
            obj.QST_CODE = item.QST_CODE;
            obj.OPT_VAL = item.OPT_VAL;
            arr.push(obj);
            //alert(obj.OPT_VAL);
        }
        return arr;
    }

    static getRealmPath() {
        let path = realm.path;
        return path;
    }

    //需要更改current_user和userinfo两张表
    static updateUserName(username) {
        let app_info_record = realm.objects(Constant.TABLE_CURRENT_USER)[0];
        let userInfo = realm.objects('USERINFO').filtered("EMP_ID='" + InitDB.getCurrentUser().empId + "' AND QST_CODE='username'")[0];
        realm.write(() => {
            app_info_record.username = username;
            userInfo.OPT_VAL = username;
        })
    }

    //更改userinfo属性
    static updateUserInfoProperty(property, value) {
        let empId = InitDB.getCurrentUser().empId;
        let app_info_record = realm.objects(Constant.TABLE_CURRENT_USER)[0];
        let userInfo = realm.objects('USERINFO').filtered("EMP_ID='" + empId + "' AND QST_CODE='" + property + "'")[0];
        realm.write(() => {
            if (userInfo) {
                userInfo.OPT_VAL = value;
            } else {  //如果属性本来为空，后台可能不传，此时需要插入
                realm.create('USERINFO', {
                    ID: '' + empId + 'userinfo' + property,
                    EMP_ID: '' + empId,
                    ACVT_CODE: 'userinfo',
                    QST_CODE: property,
                    OPT_VAL: '' + value
                });
            }
        })
    }
}

export default InitDB;
